package com.example.accessibilityhelper

import android.accessibilityservice.AccessibilityService
import android.view.accessibility.AccessibilityEvent
import java.util.ArrayDeque

abstract class Task {
    private val finishedSteps = ArrayDeque<Step>()
    private var runningStep: Step? = null
    private var readySteps = ArrayDeque<Step>()

    fun addStep(step: Step) {
        step.attach(this)
        readySteps.add(step)
    }

    fun buildTask(vararg steps: Step) {
        for (step in steps) {
            step.attach(this)
            readySteps.add(step)
        }
    }

    fun tryMatchStepOnAccessibilityEvent(service: AccessibilityService, event: AccessibilityEvent) {
        if (runningStep == null){
            next()
        }
        if (runningStep?.match(service,event) == true){
            runningStep?.execute(service,event)
        }
    }

    fun finish(step: Step) {
        runningStep = null
        finishedSteps.offerLast(step)
        next()
    }

    fun terminate() {
        runningStep = null
        readySteps.clear()
        finishedSteps.clear()
    }

    /**
     * just for notation
     */
    fun next() {
        if (runningStep == null) {
            runningStep = readySteps.poll()
            runningStep?.onStart()
            if (runningStep == null){
                Dispatcher.finishAndPromote(this)
            }
        }
    }
}